// 创建一个全新的农场（空白农场，只有两座木屋）
function createNewFarm() {
    var cell = {
        x: 0,
        y: 0,
        sheep: 0,
        pig: 0,
        cattle: 0,
        grain: 0,
        vegetable: 0,
        building: null, // null 空地 field 农田 / woodenHut 木屋 / clayHut 砖房 / stoneHouse 石屋 / stable 畜棚
        pastureIndex: null, // null 为不是牧场， 数字（从0开始）为牧场的编号
        deltaFencesNum: null // 添加为牧场时，对栅栏的使用改变量
    }

    var result = [];
    for (let index = 0; index < 5; index++) {
        var colunm = [];
        for (let j = 0; j < 3; j++) {
            const element = Object.assign({}, cell);
            element.x = index;
            element.y = j;
            colunm.push(element);
        }
        result.push(colunm);
    }

    result[0][1].building = "woodenHut";
    result[0][2].building = "woodenHut";
    return result;
}

function step1(turnNum) { // step1 表示翻出一张轮次牌，轮次turnNum从1开始
    var turnCardId = turnCardsIdList[turnNum - 1]; // 轮次turnNum从1开始,而数组从0开始
    initTurnCard(turnCardId);
    var turnCardStr = generateTurnCard(turnCardId, turnNum);
    var turnCardNode = $(turnCardStr);

    // 检查当前轮是否是收获时节
    if (isHarvestRound(turnNum)) {
        var harvest = $("<div>(收获时节)<div>");
        turnCardNode.append(harvest);
    }

    $("#turn-cards").append(turnCardNode);
    resourceIncrease();
}

function restoreTurnCards(turnCardIds) {
    turnCardIds.forEach((turnCardId, index) => {
        var turnCardStr = generateTurnCard(turnCardId, index + 1);
        var turnCardNode = $(turnCardStr);

        // 检查当前轮是否是收获时节
        if (isHarvestRound(index + 1)) {
            var harvest = $("<div>(收获时节)<div>");
            turnCardNode.append(harvest);
        }

        $("#turn-cards").append(turnCardNode);
    });
}

function goHome() {
    var nodes = $(".your-worker");
    if (nodes.length > 0) {
        nodes.remove();
    }

    window.myData.unusedWorker = window.myData.totalWorkers;
    updateResourceBar();

    dispatchEventDelay(EVENT_AFTER_GO_HOME, { workersWorkspaces: window.myData.workersWorkspaces });

    window.myData.workersWorkspaces = [];
}

function startNewRound() {
    const nextRoundIndex = window.boardData.currentRound;
    const rewards = window.myData.roundRewards[nextRoundIndex];
    if (rewards) {
        for (const [resource, amount] of Object.entries(rewards)) {
            window.myData[resource] += amount;
            alert(`你从下一轮的轮次牌上获得 ${TypeFullName[resource]} : ${amount}`);
        }
    }

    // 其他回合开始时的逻辑

    updateResourceBar()
    updateFarm();

    // 首先递增轮次计数
    window.boardData.currentRound++;  // 递增轮次计数
    // 翻开新一回合的轮次牌
    step1(window.boardData.currentRound);

    updateFutureRoundRewards();

    dispatchEvent(EVENT_START_NEW_ROUND);
}

async function endTurn() {
    goHome();

    if (isHarvestRound(window.boardData.currentRound)) {
        await handleHarvest();
    }

    // 清空新增家庭成员的婴儿状态
    window.myData.newborns = [];

    await dispatchEvent(EVENT_CURRENT_ROUND_END);

    if (window.boardData.currentRound == 14) {
        await beforeFinalScore();

        // 最后一轮的收获阶段完成，需要进行终局计分
        displayFinalScore();

        // 移除存档，下一次刷新页面会直接开始新游戏
        removeGame();
        return;
    } 
    
    startNewRound();
    saveGame();
}

async function performFeedingPhase() {
    // 成年人每人需要2个食物，婴儿每人需要1个食物
    const totalWorkers = window.myData.totalWorkers;
    const newbornCount = window.myData.newborns.length;
    const adultCount = totalWorkers - newbornCount;
    const foodNeeded = adultCount * 2 + newbornCount;

    // 检查是否有足够的食物
    if (window.myData.food >= foodNeeded) {
        if (confirm(`你有足够的食物。是否直接支付 ${foodNeeded} 个食物？`)) {
            window.myData.food -= foodNeeded;
            window.actionData.foodToPayDuringFeedingPhase = 0;
            updateResourceBar();
            return;
        }
    }

    window.actionData.foodToPayDuringFeedingPhase = foodNeeded;

    // 显示给养阶段视图
    window.actionData.status = "feedingPhase";
    updateAdditionalView();

    return new Promise((resolve) => {
        window.resolveFeedingPhase = resolve; // 保存 resolve 函数，以便在用户完成操作后调用
    });
}

// 作为updateAdditionalView对应status的func方法
function updateFeedingPhaseView() {
    $(".feeding-phase-view .needed-food").text(window.actionData.foodToPayDuringFeedingPhase);
}

async function handleHarvest() {
    // 处理农田收获
    window.myData.farmCells.forEach(column => {
        column.forEach(cell => {
            if (cell.building === "field") {
                if (cell.grain > 0) {
                    cell.grain -= 1;
                    window.myData.grain += 1;
                    dispatchEvent(EVENT_HARVEST_FOR_CELL, { cell, resourceType: 'grain' });
                }
                if (cell.vegetable > 0) {
                    cell.vegetable -= 1;
                    window.myData.vegetable += 1;
                    dispatchEvent(EVENT_HARVEST_FOR_CELL, { cell, resourceType: 'vegetable' });
                }
            }
        });
    });

    updateFarm();
    updateResourceBar();

    await dispatchEvent(EVENT_HARVEST_AFTER_REAP);

    await waitForUIRefresh();

    await performFeedingPhase();

    // 处理动物繁殖
    const animalTypes = ['sheep', 'pig', 'cattle'];
    animalTypes.forEach(animal => {
        let totalAnimals = window.myData.farmCells.reduce((sum, column) => {
            return sum + column.reduce((colSum, cell) => colSum + cell[animal], 0);
        }, 0);

        if (totalAnimals >= 2) {
            var stop = false;
            for (let i = 0; i < window.myData.farmCells.length; i++) {
                const column = window.myData.farmCells[i];
                for (let j = 0; j < column.length; j++) {
                    const cell = column[j];
                    if (cell[animal] > 0) {
                        cell[animal] += 1;
                        stop = true;
                        break;
                    }
                }
                if (stop) {
                    break;
                }
            }
            if (stop == false) { 
                // 农场中没有与当前动物种类相同的动物，但是又需要繁殖（比如在其他职业卡或者发展卡上有动物）
                window.myData.farmCells[0][0][animal] += 1;
            }
        }
    });

    updateFarm();
    updateResourceBar();
}

function handleDirectPayment() {
    const foodNeeded = window.actionData.foodToPayDuringFeedingPhase;

    if (window.myData.food > 0) {
        const foodPaid = Math.min(window.myData.food, foodNeeded);
        window.myData.food -= foodPaid;
        updateResourceBar();
        var foodToPay = foodNeeded - foodPaid;
        window.actionData.foodToPayDuringFeedingPhase = foodToPay;
        updateFeedingPhaseView();

        if (foodToPay <= 0) {
            completeFeedingPhase();
        }
    } else {
        alert("您的食物不够给养");
    }
}

function handleAcquireDisadvantage() {
    var foodToPay = window.actionData.foodToPayDuringFeedingPhase;
    if (foodToPay > 0) {
        window.myData.disadvantages += foodToPay;
        window.actionData.foodToPayDuringFeedingPhase = 0;
        updateResourceBar();
        completeFeedingPhase();
    }
}

function completeFeedingPhase() {
    endAction();

    if (window.resolveFeedingPhase) {
        window.resolveFeedingPhase();
        window.resolveFeedingPhase = null;
    }
}